package io.wongxd.demo.page

import android.Manifest
import android.util.Log
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.*
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.derivedStateOf
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.lifecycle.lifecycleScope
import io.wongxd.demo.AppBtn
import io.wongxd.solution.baseView.BaseComposeToolBarFgt
import io.wongxd.solution.compose.custom.ScrollSelector
import io.wongxd.solution.logger.Logger
import io.wongxd.solution.logger.WLogUtil
import io.wongxd.solution.permission.PermissionCommons
import io.wongxd.solution.permission.PermissionCommons.ReqPermission
import io.wongxd.solution.permissionFlow.PermissionFlow
import io.wongxd.solution.universalCache.CachedSourceNoParams
import io.wongxd.solution.universalCache.FromCache
import io.wongxd.solution.universalCache.getByNorParams
import kotlinx.coroutines.flow.launchIn
import kotlinx.coroutines.flow.onEach
import kotlinx.coroutines.launch
import java.util.concurrent.atomic.AtomicInteger

class FgtNormal : BaseComposeToolBarFgt() {
    override fun lazyInit() {
        observeUpdates()

        permissionFlow.getPermissionState(Manifest.permission.RECORD_AUDIO)
            .onEach {
                val temp = "全局观察：${it.permission} - ${it.isGranted}"
                WLogUtil.d(temp)
                perDesStr.value = temp
            }
            .launchIn(viewLifecycleOwner.lifecycleScope)
    }

    override val title: String
        get() = "FgtNormal"

    private val perDesStr = mutableStateOf("")
    private val permissionFlow = PermissionFlow.getInstance()


    @Composable
    override fun Render() {
        Column(
            modifier = Modifier
                .fillMaxSize()
                .background(Color.White)
        ) {
            val dens = LocalDensity.current
            val statusBarsHeight = WindowInsets.statusBars.getTop(dens)
            val des = "状态栏高度:${statusBarsHeight}  FgtNormal"
            Logger.d(des)
            Text(text = des)

            val perState =
                permissionFlow.getPermissionState(Manifest.permission.RECORD_AUDIO).collectAsState()
            val localDes = remember {
                derivedStateOf {
                    val perDes =
                        "权限观察:${perState.value.permission} - ${perState.value.isGranted}"
                    WLogUtil.d(perDes)
                    perDes
                }
            }

            Text(text = "本地：${localDes.value}", modifier = Modifier.padding(top = 20.dp))

            Text(text = "全局：${perDesStr.value}", modifier = Modifier.padding(top = 20.dp))


            AppBtn(text = "改变状态栏颜色") {
                statusBarColorByCompose = listOf(Color.Black, Color.Yellow, Color.Red, Color.Green, Color.White).random()
                statusBarDarkIconByCompose = listOf(true, false).random()
                resetStatusBarMsState.value = System.currentTimeMillis()
            }

            var reqMs by remember {
                mutableStateOf(0L)
            }

            AppBtn(text = "权限通过时间更新") {
                val ms = System.currentTimeMillis()
                reqMs = ms
                WLogUtil.d("权限,$ms")
            }

            ReqPermission(
                permissionsToRequest = PermissionCommons.REQUIRED_RECORD_AUDIO_PERMISSIONS,
                reqWhenFirstEnter = false,
                refreshReqMs = reqMs
            ) {
                WLogUtil.d("权限结果,$it")
            }

//            Text(
//                "新拟态",
//                style = AppThemeHolder.textStyle.sp14.black(),
//                modifier = Modifier
//                    .wrapContentSize()
//                    .padding(5.dp)
//                    .neumorphic(neuShape = Pressed.Rounded(20.dp))
//            )

            ScrollSelector(
                items = (0..99).toList().map { it.toString() },
                modifier = Modifier.fillMaxWidth(),
                onItemSelected = { i, s ->
                    WLogUtil.d("选中:$i，$s")
                    launchAndObserveParallelRequests()
                })
        }
    }

    private var str1 by mutableStateOf("")
    private var str2 by mutableStateOf("")

    private val taskInvocationCnt = AtomicInteger()
    private val longRunningTask = {
        Thread.sleep(1000)
        Log.i("test_", "test_ longRunningTask")
        taskInvocationCnt.incrementAndGet()
    }
    private val source = CachedSourceNoParams(longRunningTask)

    private fun launchAndObserveParallelRequests() {
        lifecycleScope.launch {
            source.getByNorParams(FromCache.IF_HAVE)
                .collect {
                    Log.i("test_", "test_ collect 1: $it")
                    str1 = "Ready, invocation count: $it"
                }
            source.getByNorParams(FromCache.IF_HAVE)
                .collect {
                    Log.i("test_", "test_ collect 2: $it")
                    str1 = "Ready, invocation count: $it"
                }
            source.getByNorParams(FromCache.IF_HAVE)
                .collect {
                    Log.i("test_", "test_ collect 3: $it")
                    str1 = "Ready, invocation count: $it"
                }
        }
    }

    private fun observeUpdates() {
        lifecycleScope.launch {
            source.updates.collect {
                Log.i("test_", "test_ collect updates: $it")
                str2 = "Update: $it"
            }
        }
    }

    @Preview(showBackground = true, backgroundColor = 0xffffffff)
    @Composable
    fun RenderPreView() {

    }
}